#!/usr/bin/env python

import os, sys, time, string, getopt, signal, subprocess, logging, logging.handlers, random

########## Print Usage Information #############
def usage():
  print "Usage: pid.py [-i interval] [-d]\n"
  print "-i, --interval: set sampling interval (in secs)\n"
  print "-d, --debug: set debugging mode\n"
  print "--gdir: set the directory of gmetric\n"
  print "--log: set the filename of log\n"


######## Collect data from iostat ##############
def collectData(devlist, maxline):
  # collect data from devices #
  metindex = [3, 5, 7, 9] 
  metlist = []
  f = open('/proc/diskstats', 'r');
  fwrong = 1
  try:
    lines = f.readlines();
  except Exception, e:
    fwrong = 0
  finally:
    f.close()
 
  if (fwrong == 0 or len(lines) != maxline):
    logger.info("Read files error!")
    return [0, metlist]

  for i in devlist:
    line = lines[i]
    res = string.split(line)
    if (len(res) != 14 or not res[3].isdigit()):
      logger.info('Read wrong line in collectData()')
      return [0, metlist]
    metdev = []
    for j in metindex:
      metdev.append(float(res[j])) 
    metdev.append(res[2])
    metlist.append(metdev)

  return [1, metlist] 

############# Main Program ##################3333

try:
  opts, args = getopt.getopt(sys.argv[1:], "i:d", ["interval=", "debug=", "idir=", "gdir=", "log="])
except getopt.GetoptError, err:
  print str(err)
  usage()
  sys.exit(2)

# default value
interval = 5 
debug = 0
gmetricdir = "."
logfile = "/var/log/diskscriptlog/disk_script.log"
for o, a in opts:
  if o in ("-i", "--interval"):
    interval = int(a)
  elif o in ("-d", "--debug"):
    debug = 1
  elif o in ("--idir"):
    iostatdir = a 
  elif o in ("--gdir"):
    gmetricdir = a
  elif o in ("--log"):
    logfile = a

cmdGmetric = gmetricdir+"/gmetric"
if os.path.exists(cmdGmetric) == False:
  print "Cannot find gmetric in the path "+gmetricdir
  sys.exit(2)

logger = logging.getLogger('DiskScriptLogger')
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(
    logfile, maxBytes=1024*1024, backupCount=5)
logger.addHandler(handler)

numMetrics = 4
gangliaMetrics = { "name": ["req_read", "bytes_read", "req_write", "bytes_write"], \
		   "unit": ["iops", "bytes/s", "iops", "bytes/s"], \
	   	   "type": ["double", "double", "double", "double"]}
k = 1
cnt = 0
while (1):
  cmdExec = cmdGmetric + " --name="+gangliaMetrics["name"][0]+":1000:378" \
     + " --value="+ str(k) +\
    " --type=" + gangliaMetrics["type"][0] + " --units=\"" + gangliaMetrics["unit"][0] + "\""
  if debug == 1:
     print "cmdExec="+cmdExec
  gmetricResult = os.system(cmdExec)
  cmdExec = cmdGmetric + " --name="+gangliaMetrics["name"][0]+":1000:798" \
     + " --value="+ str(k) +\
    " --type=" + gangliaMetrics["type"][0] + " --units=\"" + gangliaMetrics["unit"][0] + "\""
  if debug == 1:
     print "cmdExec="+cmdExec
  gmetricResult = os.system(cmdExec)
 
  cnt = cnt + 1
  if cnt == 3:
    cnt = 0
    k = k * 2 
    if k > 1000:
      k = 1
  time.sleep(interval)
